<template>
  <div>
    <!-- 抄表数据 -->

    <!-- 搜索框 -->
    <el-form ref="SearchForm" :model="SearchForm" label-width="60px">
      <el-row>

        <el-col :span="6">
          <el-form-item label="编号：" label-width="100px">
            <el-input placeholder="请输入收费项目名" v-model="SearchForm.searchByBlockCode" />
          </el-form-item>
        </el-col>

        <el-col :span="7">
          <el-form-item label="请选择收费项：" label-width="160px">
            <el-select v-model="SearchForm.searchByItemName" placeholder="请选择" style="width:230px">
              <el-option v-for="key in feeItemName" :key="key" :label="key" :value="key">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item>
            <el-button type="primary" @click="searchMassage" icon="el-icon-search">搜索</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item>
            <el-button @click="resetFields" icon="el-icon-refresh">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 下载 -->
    <el-button type="primary" @click="downloadFileTemplate" icon="el-icon-download">下载模板</el-button>

    <!-- 上传 -->
    <el-button type="primary" @click="beforeUpload" icon="el-icon-upload2">上传</el-button>

    <el-dialog title="提示" :visible.sync="dialogUploadVisible" width="50%" :before-close="handleClose">
      <el-steps :active="active" finish-status="success">
        <!-- 上传文件 -->
        <el-step title="上传文件"></el-step>
        <el-step title="导入结果"></el-step>
      </el-steps>

      <el-upload class="upload-demo" drag :on-success="handleUploadSuccess" action="http://localhost:8080/upload" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖-到此处，或<em>点击上传</em></div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUploadVisible = false">取 消</el-button>
        <el-button v-if="active != 1" @click="next">下一步</el-button>
        <el-button type="primary" v-if="active == 1" @click="analyseExcelFile">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 数据展示--表格 -->
    <el-table :data="tableData" border style="width: 100%;border-radius: 10px; margin-top: 10px" :header-cell-style="{
          background: '#1890ff',
          color: 'white',
          'text-align': 'center',
        }" :cell-style="{
          'text-align': 'center',
        }">
      <el-table-column type="index" label="序号" align="center">
      </el-table-column>
      <el-table-column prop="resourceName" label="编号"  align="center">
      </el-table-column>

      <el-table-column prop="feeItemName" label="费用类型"  align="center">
      </el-table-column>
      <el-table-column prop="lastIndex" label="上期读数"  align="center">
      </el-table-column>
      <el-table-column prop="lastIndexDate" label="上期读数时间" align="center">
      </el-table-column>

      <el-table-column prop="currentIndex" label="本期读数" align="center">
      </el-table-column>

      <el-table-column prop="currentIndexDate" label="本期读数时间"  align="center">
      </el-table-column>

      <el-table-column prop="multiple" label="倍率" align="center">
      </el-table-column>

      <el-table-column prop="loss" label="损耗" align="center">
      </el-table-column>

      <el-table-column prop="result" label="最终数量" align="center">
      </el-table-column>
      <el-table-column prop="name" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="beroreSubmitModifyForm(scope.row)" size="small">编辑</el-button>
          <el-button type="text" @click="beforeDeleteItemById(scope.row)" size="small" style="color:#FF6459">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑" :visible.sync="dialogModifyVisible" style="font-weight:bold">
      <el-form :model="ruleModifyForm" :rules="rules" ref="ruleModifyForm" label-width="120px" class="demo-ruleForm">

        <el-form-item label="资源名" prop="ItemType">
          <el-input v-model="ruleModifyForm.resourceName" disabled="false"></el-input>
        </el-form-item>

        <el-form-item label="资源类型" prop="ItemName">
          <el-input v-model="ruleModifyForm.feeItemName" disabled></el-input>
        </el-form-item>

        <el-form-item label="上期度数" prop="price">
          <el-input v-model="ruleModifyForm.lastIndex" placeholder="请输入单价"></el-input>
        </el-form-item>

        <el-form-item label="上期读表时间" prop="numType">
          <el-date-picker v-model="ruleModifyForm.lastIndexDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="本期度数" prop="period">
          <el-input v-model="ruleModifyForm.currentIndex" placeholder="请输入读数"></el-input>
        </el-form-item>

        <el-form-item label="本期读表时间" prop="lateFeeEnable">
          <el-date-picker v-model="ruleModifyForm.currentIndexDate" type="date" placeholder="选择日期">
          </el-date-picker>

        </el-form-item>

        <el-form-item label="倍率">
          <el-input v-model="ruleModifyForm.multiple" placeholder="请输入比例">

          </el-input>
        </el-form-item>

        <el-form-item label="损耗">
          <el-input v-model="ruleModifyForm.loss" placeholder="请输入单价"></el-input>
        </el-form-item>

        <el-form-item label="最终数量">
          <el-input v-model="ruleModifyForm.result" disabled></el-input>
        </el-form-item>

        <el-form-item style="margin-top:30px;margin-left:400px">
          <el-button type="primary" @click="submitModifyForm">确定</el-button>
          <el-button @click="dialogModifyVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页 -->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[5, 10,15,20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
export default {
  data() {
    return {
      url_Get_getPaymentMeterList: "http://localhost:8080/getPaymentMeterList",

      // 下载文件
      url_Get_downloadTemplate: "http://localhost:8080/downloadTemplate",

      // 分析Excel到数据库
      url_Post_analyseExcelFileToDB: "http://localhost:8080/analyseExcelFile",

      url_Post_modifyPaymentMeter: "http://localhost:8080/modifyPaymentMeter",

      // 删除数据
      url_Get_deletePaymentMeterById:
        "http://localhost:8080/deletePaymentMeterById",

      // 搜索框搜索数据的表单
      SearchForm: {
        searchByBlockCode: "",
        searchByItemName: "",
      },
      // 收费项下拉框
      feeItemName: ["测试抄表燃气费", "空调费", "抄表水费"],

      // 上传文件
      uploadForm: {
        filePath: "",
      },
      fileList: [],

      tableData: [],

      // 下载对话框
      dialogDownloadVisible: false,
      downloadFile: "",

      // 上传对话框
      dialogUploadVisible: false,
      active: 0,
      // 编辑对话框
      dialogModifyVisible: false,

      ruleModifyForm: {},

      deleteItemById: "",

      // 分页数据
      pageNum: 1,
      pageSize: 5,
      total: "",
    };
  },

  methods: {
    // 分页
    handleSizeChange(val) {
      this.getPaymentMeterList(this.pageNum, val, "", "");
    },
    handleCurrentChange(val) {
      this.getPaymentMeterList(val, this.pageSize, "", "");

    },

    searchMassage() {
      this.getPaymentMeterList(
        this.pageNum,
        this.pageSize,
        this.SearchForm.searchByBlockCode,
        this.SearchForm.searchByItemName
      );
    },

    // 重置字段
    resetFields() {
      (this.SearchForm.searchByBlockCode = ""),
        (this.SearchForm.searchByItemName = ""),
        this.getPaymentMeterList(1, 5, "", "");
    },

    next() {
      this.active++;
    },

    // 下载文件
    downloadFileTemplate() {
      this.$http
        .get(this.url_Get_downloadTemplate, {
          responseType: "blob",
        })
        .then((response) => {
          // 创建一个URL对象
          const url = window.URL.createObjectURL(new Blob([response.data]));
          // 创建一个<a>标签，设置其href属性为下载的URL
          const link = document.createElement("a");
          link.href = url;
          // 设置下载文件的名称
          link.setAttribute("download", "抄表数据导入模板.xlsx");
          // 将<a>标签添加到文档中
          document.body.appendChild(link);
          // 模拟点击<a>标签来触发文件下载
          link.click();
          // 完成后，清除URL对象和<a>标签
          window.URL.revokeObjectURL(url);
          document.body.removeChild(link);
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    // 上传成功后返回文件路径
    handleUploadSuccess(response) {
      this.uploadForm.filePath = response; // 将上传成功的文件路径保存到表单数据中
    },

    // 解析并添加到数据库中
    analyseExcelFile() {
      this.dialogUploadVisible = false;

      this.$http
        .get(this.url_Post_analyseExcelFileToDB, {
          params: {
            filePath: this.uploadForm.filePath,
          },
        })
        .then((result) => {
          this.$message({
            message: "添加成功",
            type: "success",
          });

          this.getPaymentMeterList(this.pageNum, this.pageSize, "", "");
        })
        .catch((err) => {
          this.$message({
            message: "获取列表失败",
            type: "error",
          });
        });
    },

    beforeUpload() {
      if (this.dialogUploadVisible == false) {
        this.dialogUploadVisible = true;
      }

      const isJPG = file.type === "image/jpeg";
      if (!isJPG) {
        this.$message.error("只能上传  格式的图片");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB");
      }
      return isJPG && isLt2M;
    },

    // 获取列表数据
    getPaymentMeterList(pageNum, pageSize, blockCode, feeItemName) {
      this.$http
        .get(this.url_Get_getPaymentMeterList, {
          params: {
            pageNum: pageNum,
            pageSize: pageSize,
            blockCode: blockCode,
            feeItemName: feeItemName,
          },
        })
        .then((result) => {
          this.tableData = result.data.data.list;
          this.pageNum = result.data.data.pageNum;
          this.pageSize = result.data.data.pageSize;
          this.total = result.data.data.total;
        })
        .catch((err) => {
          this.$message({
            message: "获取列表失败",
            type: "error",
          });
        });
    },

    // 编辑数据
    beroreSubmitModifyForm(row) {
      this.ruleModifyForm = row;
      if (this.dialogModifyVisible == false) {
        this.dialogModifyVisible = true;
      }
    },
    submitModifyForm() {
      this.$http
        .post(this.url_Post_modifyPaymentMeter, this.ruleModifyForm)
        .then((result) => {
          this.getPaymentMeterList(this.pageNum, this.pageSize, "", "");
          this.dialogModifyVisible = false;
          this.$message({
            type: "success",
            message: "修改成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "修改失败!",
          });
        });
    },
    modifyResult(lastIndex, currentIndex, multiple, loss) {
      this.ruleModifyForm.result =
        (currentIndex - lastIndex) * multiple + parseInt(loss);
    },

    // 删除之前
    beforeDeleteItemById(row) {
      this.deleteItemById = row.id;
      console.log(this.deleteItemById);

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deletePanymentMeterById();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 根据id删除数据
    deletePanymentMeterById() {
      this.$http
        .get(this.url_Get_deletePaymentMeterById, {
          params: {
            id: this.deleteItemById, //
          },
        })
        .then(() => {
          this.getPaymentMeterList(this.pageNum, this.pageSize, "", "");
        })
        .catch(() => {});
    },
  },
  watch: {
    // 监听上期读数
    "ruleModifyForm.lastIndex"(newval, oldval) {
      if (newval != null && newval != "") {
        this.modifyResult(
          newval,
          this.ruleModifyForm.currentIndex,
          this.ruleModifyForm.multiple,
          this.ruleModifyForm.loss
        );
      }
    },
    // 监听本期读数
    "ruleModifyForm.currentIndex"(newval, oldval) {
      if (newval != null && newval != "") {
        this.modifyResult(
          this.ruleModifyForm.lastIndex,
          newval,
          this.ruleModifyForm.multiple,
          this.ruleModifyForm.loss
        );
      }
    },
    // 监听倍率
    "ruleModifyForm.multiple"(newval, oldval) {
      if (newval != null && newval != "") {
        this.modifyResult(
          this.ruleModifyForm.lastIndex,
          this.ruleModifyForm.currentIndex,
          newval,
          this.ruleModifyForm.loss
        );
      }
    },
    // 监听损耗值
    "ruleModifyForm.loss"(newval, oldval) {
      if (newval != null && newval != "") {
        this.modifyResult(
          this.ruleModifyForm.lastIndex,
          this.ruleModifyForm.currentIndex,
          this.ruleModifyForm.multiple,
          newval
        );
      }
    },
  },

  mounted() {
    this.getPaymentMeterList(this.pageNum, this.pageSize, "", "");
  },
};
</script>

<style>
</style>